import React, { useContext, useRef, useState } from 'react';

import cls from 'classnames';

import { Button, message, Input, InputRef } from 'antd';

import { DictionaryContext } from '@/pages/SystemController/DictionaryTreeController/hooks';

import {
  SearchOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';

import { TypographyTitle } from '@/components/Typography';
import { DictionaryAdd } from '@/pages/SystemController/DictionaryTreeController/components/DictionaryTableAdd';
import { IDictionaryTableHeader } from '@/pages/SystemController/DictionaryTreeController/type';

export const DictionaryTableHeader: React.FC<IDictionaryTableHeader> = ({
  dataSource,
}) => {
  const {
    prefixCls,
    selectKeys,
    commonDispatch,
    reloadTableDataSource,
  } = useContext(DictionaryContext);
  const searchRef = useRef<InputRef>(null);
  const [showAppendDictionary, setShowAppendDictionary] = useState(false);

  const onCloseAppendDictionary = () => {
    setShowAppendDictionary(false);
  };

  const onOpenAppendDictionary = () => {
    if (selectKeys?.[0]) {
      setShowAppendDictionary(true);
    } else {
      message.warning('请先选择字典类型！');
    }
  };

  const onSearch = () => {
    const value = (searchRef.current!.input as HTMLInputElement).value;

    let expandedRowKeys: any = [];

    let tileDataSource: any = [];

    const tileArray = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children) {
          tileArray(item?.children);
        }
        if (item) {
          tileDataSource.push(item);
        }
      });
    };

    if (dataSource) {
      tileArray(dataSource);
    }

    const getParentKey = (id: string) => {
      let idArray: any = [];

      const loop = (ids: string) => {
        tileDataSource?.forEach((item: any) => {
          if (item?.id == ids) {
            idArray.push(item?.id);

            if (item?.pID) {
              loop(item?.pID);
            }
          }
        });
      };

      loop(id);

      return idArray;
    };

    const findExpandedRowKeys = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.name?.includes(value)) {
          expandedRowKeys.push(item?.id);

          if (item?.pID) {
            expandedRowKeys = [...expandedRowKeys, ...getParentKey(item?.pID)];
          }
        }
      });
    };

    findExpandedRowKeys(tileDataSource);

    commonDispatch({
      type: 'edit-searchTableValue',
      payload: value,
    });

    commonDispatch({
      type: 'edit-expandedRowKeys',
      payload: Array.from(new Set([...expandedRowKeys])),
    });
  };

  return (
    <>
      <div className={cls(prefixCls + 'table-header')}>
        <TypographyTitle
          level={4}
          style={{
            margin: 0,
          }}
        >
          数据字典
        </TypographyTitle>

        <div className={cls(prefixCls + 'table-search')}>
          <Input
            placeholder={'请按名称搜索'}
            ref={searchRef}
            allowClear
            onPressEnter={onSearch}
            suffix={<SearchOutlined />}
            addonAfter={
              <ReloadOutlined
                onClick={() => reloadTableDataSource(selectKeys?.[0])}
              />
            }
          />
          <Button
            type={'primary'}
            icon={<PlusOutlined />}
            onClick={onOpenAppendDictionary}
            style={{
              marginLeft: 12,
            }}
          >
            添加
          </Button>
        </div>
      </div>

      {showAppendDictionary && (
        <DictionaryAdd
          dataSource={dataSource}
          onClose={onCloseAppendDictionary}
        />
      )}
    </>
  );
};
